import GlobalConfig from "../../common/config/GlobalConfig";
import { BehaviorTree } from "../../libs/behavior/BehaviorTree";
import { BehaviorTreeBuilder } from "../../libs/behavior/BehaviorTreeBuilder";
import { AbortTypes } from "../../libs/behavior/composites/AbortTypes";
import { TaskStatus } from "../../libs/behavior/TaskStatus";

class State{
    fatigue:number = 10;
    static readonly MAX_FATIGUE = 10;
    thirst:number = 10;
    static readonly MAX_THIRST = 10;
    gold:number = 10;
    static readonly MAX_GOLD = 10;
}

export default class AiComponent{
    private _tree: BehaviorTree<AiComponent>;
    private _distanceToNextLocation: number = 10;
    private state = new State();
   

    public update(deltaTime:number){
        GlobalConfig.deltaTime = deltaTime;
        if (this._tree)
            this._tree.tick();
    }

    public start(){
        let builder = BehaviorTreeBuilder.begin(this);

        builder.selector(AbortTypes.Self);

        // 睡觉最重要
        builder.conditionalDecoratorR(m => m.state.fatigue >= State.MAX_FATIGUE, false);
        builder.sequence(AbortTypes.LowerPriority)
            .logAction("-- 累了,准备回家")
            .logAction("-- 准备上床")
            .action(m => m.sleep())
            .endComposite();

        // 喝水第二重要
        builder.conditionalDecoratorR(m => m.state.thirst >= State.MAX_THIRST, false);
        builder.sequence(AbortTypes.LowerPriority)
            .logAction("-- 渴了! 准备喝水")
            .logAction("-- 开始喝水")
            .action(m => m.drink())
            .endComposite();

        // 存钱第三重要
        builder.conditionalDecoratorR(m => m.state.gold >= State.MAX_GOLD, false);
        builder.sequence(AbortTypes.LowerPriority)
            .logAction( "--- 背包满了，准备去银行存钱." )
            .logAction( "--- 开始存钱!" )
            .action( m => m.depositGold() )
            .endComposite();


        builder.endComposite();

        this._tree = builder.build();

        window["tree"] = this._tree;
    }


    private drink(): TaskStatus{
        console.log(`开始喝水, 口渴程度: ${this.state.thirst}`);

        if( this.state.thirst == 0 )
            return TaskStatus.Success;

        this.state.thirst--;
        return TaskStatus.Running;
    }

    private sleep(): TaskStatus{
        console.log(`开始睡觉, 当前疲惫值: ${this.state.fatigue}`);

        if (this.state.fatigue == 0)
            return TaskStatus.Success;
        
        this.state.fatigue--;
        return TaskStatus.Running;
    }

   
    private depositGold(): TaskStatus{
        this.state.gold = 0;

        console.log(`存钱进入银行. `);

        return TaskStatus.Success;
    }
}
